package gw.com.android.ui.me_post;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gwtsz.gts2.hx.R;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.ui.onlive.Comment;
import gw.com.android.ui.onlive.DiscussData;
import gw.com.android.ui.views.ExpandableTextView;
import gw.com.android.ui.views.ImageWatcher;
import gw.com.android.utils.CommentsHelper;
import gw.com.android.utils.CopyShowerUtil;
import gw.com.android.utils.FontUtils;
import gw.com.android.utils.ImageLayoutHelper;
import gw.com.android.utils.PackStatis;
import www.com.library.dialog.ToastPopWindow;

public class MyPostAdapter extends RecyclerView.Adapter<MyPostAdapter.MyPostViewHolder> {

    /**
     * 左边菜单栏适配器数据对象
     */
    private Activity mContext;
    private LayoutInflater mInflater;
    private ImageWatcher watcher;
    //用一个map保存日期是否显示
    private Map<Integer, String> dateVisibleStatus = new HashMap<>();
    private final static String VISIBLE_STATUS_NONE = "none";// 未指定显示状态
    private final static String VISIBLE_STATUS_TRUE = "true";// 显示
    private final static String VISIBLE_STATUS_FALSE = "false";// 不显示

    private List<DiscussData> mDatas = new ArrayList<>();
    Typeface font;

    public MyPostAdapter(Activity context) {
        mInflater = context.getLayoutInflater();
        mContext = context;
        font = FontUtils.getDIN_MediumFont(mContext);
        initDateVisibleStatus();
    }

    public void setWatcher(ImageWatcher watcher) {
        this.watcher = watcher;
    }

    private void initDateVisibleStatus() {
        dateVisibleStatus.clear();
        for (int i = 1; i <= mDatas.size(); i++) {
            dateVisibleStatus.put(i, VISIBLE_STATUS_NONE);// 默认都不显示
        }
    }

    private void addDateVisibleStatus(List<DiscussData> list) {
        for (int i = 1; i <= list.size(); i++) {
            dateVisibleStatus.put(i, VISIBLE_STATUS_NONE);// 默认都不显示
        }
    }

    /**
     * 下拉刷新替换新数据
     */
    public void setData(List<DiscussData> list) {
        List<DiscussData> temp = new ArrayList<>();
        temp.add(new DiscussData());//为listHeader留下空位
        temp.addAll(list);
        mDatas = temp;
        // 由于第一个是 head,所以在这里clone一份list，然后重新排
        initDateVisibleStatus();
        notifyDataSetChanged();
    }

    /**
     * 下拉刷新追加数据
     */
    public void addData(List<DiscussData> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        if (mDatas == null) {
            mDatas = list;
        } else {
            mDatas.addAll(list);
        }
        addDateVisibleStatus(list);
        notifyDataSetChanged();
    }

    /**
     * 根据position返回界面item数据对象
     */
    public DiscussData getItem(int position) {
        if (mDatas != null) {
            if (position >= 0 && position < mDatas.size()) {
                return mDatas.get(position);
            }
        }
        return null;
    }

    @Override
    public MyPostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView;
        if (viewType == VIEW_TYPE_0)
            itemView = mInflater.inflate(R.layout.list_item_post_1, parent, false);
        else
            itemView = mInflater.inflate(R.layout.list_item_post_2, parent, false);
        return new MyPostViewHolder(itemView);
    }

    private final static int VIEW_TYPE_0 = 0x01;
    private final static int VIEW_TYPE_others = 0x02;

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return VIEW_TYPE_0;
        } else {
            return VIEW_TYPE_others;
        }
    }

    @Override
    public void onBindViewHolder(MyPostViewHolder holder, int position) {
        MyPostViewHolder mHolder = holder;
        DiscussData mItem = getItem(position);//item 复用

        if (null != mItem) {
            if (position == 0) {//list中index为0 的，是list头
                //头里面，只需要设置按钮的点击事件
                holder.ll_post.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PackStatis.getToService("clickPublishPost", PackStatis.EventCategory.ME.getValue(), null, null);
                        //点击这个，进入我要发帖界面
                        if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_REAL) {
                            new ToastPopWindow(mContext, mContext.getString(R.string.home_discuss_not_real_2)).show();
                            return;
                        }
                        ActivityManager.showDiscussAdd((Activity) mContext);
                    }
                });
            } else {
                //时间解析
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
                df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
                String day, month, hourMinute;
                try {
                    Date date = df.parse(mItem.showDate);
                    df = new SimpleDateFormat("dd");//日
                    day = df.format(date);
                    df = new SimpleDateFormat("MM");//月
                    month = df.format(date);
                    df = new SimpleDateFormat("HH:mm");// 时分
                    hourMinute = df.format(date);
                } catch (ParseException e) {
                    day = "";
                    month = "";
                    hourMinute = "";
                    e.printStackTrace();
                }

                //上一个item的日月
                DiscussData mItem_last = getItem(position - 1);
                df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
                String day_last, month_last;
                try {
                    Date date = df.parse(mItem_last.showDate);
                    df = new SimpleDateFormat("dd");//日
                    day_last = df.format(date);
                    df = new SimpleDateFormat("MM");//月
                    month_last = df.format(date);
                } catch (Exception e) {
                    day_last = "";
                    month_last = "";
                }

                Log.d("daytag", month + "" + day);
                String b = dateVisibleStatus.get(position);
                if (VISIBLE_STATUS_NONE.equals(b)) {//如果未指定，那么就进入判断逻辑
                    // 如果是不显示的状态，那么判定，要不要让它显示
                    // 模仿微信那样的日期显示。 从上到下，如果日期相同，就只显示第一个。
                    if (day.equals(day_last) && month.equals(month_last)) {//如果两个都相同，那就说明是同一个月的同一天发的
                        hideDate(mHolder);
                        dateVisibleStatus.put(position, VISIBLE_STATUS_FALSE);
                    } else {
                        showDate(mHolder);
                        dateVisibleStatus.put(position, VISIBLE_STATUS_TRUE);
                    }
                } else {// 如果指定了，那么久按照指定的状态处理
                    if (Boolean.valueOf(b)) {
                        showDate(mHolder);
                    } else {
                        hideDate(mHolder);
                    }
                }

                //日月 时分
                mHolder.tv_time.setText(hourMinute);
                mHolder.tv_day.setTypeface(font);
                mHolder.tv_day.setText(day);

                mHolder.tv_month.setText(month + "月");
                mHolder.tv_month.setTypeface(font);
                //置顶 精华
                //区分是不是置顶帖
                int sorted = mItem.sorted;
                if (sorted == 1) {
                    mHolder.tv_sort_1.setVisibility(View.VISIBLE);
                } else {
                    mHolder.tv_sort_1.setVisibility(View.GONE);
                }
                //区分是不是精华帖
                int best = mItem.best;
                if (best == 1) {
                    mHolder.tv_best.setVisibility(View.VISIBLE);
                } else {
                    mHolder.tv_best.setVisibility(View.GONE);
                }

                // 帖子内容
                holder.mContentview.setConvertText(true, mItem.remark);
                new CopyShowerUtil(mContext, mHolder.expandable_text);
                //在这里获得，单张图的宽高，因为多张图，不进行特别处理
                //帖子图片
                String s = mItem.tradeImgs;
                if (TextUtils.isEmpty(s)) {//为了兼容旧数据，必须这么做（因为旧的数据并没有tradeImgs这个字段，所以必须手动造）
                    String tradeImg = mItem.tradeImg;
                    s = "[\"" + tradeImg + "\"]";
                }
                final List<ImageView> images = new ArrayList<>();
                final List<String> urlList = new ArrayList<>();
                mHolder.ll_trade_image.removeAllViews();
                mHolder.ll_trade_image_for_only_one.removeAllViews();
                if (!TextUtils.isEmpty(s)) {
                    Type type = new TypeToken<ArrayList<String>>() {
                    }.getType();
                    List<String> shaidanImageList = new Gson().fromJson(s, type);//GSON解析数组的方式也是很诡异，和Fastjson完全不同
                    if (shaidanImageList.size() == 1) {//如果不包含中括号，就是只有一张图 //判断单图多图，不能用这个了
                        mHolder.ll_trade_image.setVisibility(View.GONE);
                        mHolder.ll_trade_image_for_only_one.setVisibility(View.VISIBLE);
                        ImageLayoutHelper.getInstance(watcher).setSizeofSingleImg(mContext, mItem.imgSize);
                        ImageLayoutHelper.getInstance(watcher).addImageIntoLayout(mContext, 0, mHolder.ll_trade_image_for_only_one, shaidanImageList.get(0), images, urlList, true);

                    } else {//否则就是多张图的情况，要进行JSON解析 ，json大概是这样的["1.png","2.png"]
                        mHolder.ll_trade_image.setVisibility(View.VISIBLE);
                        mHolder.ll_trade_image_for_only_one.setVisibility(View.GONE);

                        for (int i = 0; i < shaidanImageList.size(); i++) {//轮流创建imageView并且加载到布局中
                            ImageLayoutHelper.getInstance(watcher).addImageIntoLayout(mContext, i, mHolder.ll_trade_image, shaidanImageList.get(i), images, urlList, false, computeImageLayoutMaxWidth());
                        }
                    }
                }

                //添加评论
                List<Comment> comments = mItem.comments;
                mHolder.ll_comments.removeAllViews();
                CommentsHelper.getInstance().addComment(mContext, mHolder.ll_comments, mInflater, comments, mHolder.iv_triangle);

                //处理分割线
                if (comments == null || comments.size() == 0)// 如果是最后一项，就隐藏分割线
                    mHolder.ll_comments.setVisibility(View.GONE);
                else {
                    mHolder.ll_comments.setVisibility(View.VISIBLE);
                }

            }
        }
    }

    private void showDate(MyPostViewHolder mHolder) {
        mHolder.tv_day.setVisibility(View.VISIBLE);
        mHolder.tv_month.setVisibility(View.VISIBLE);
    }

    private void hideDate(MyPostViewHolder mHolder) {
        mHolder.tv_day.setVisibility(View.INVISIBLE);
        mHolder.tv_month.setVisibility(View.INVISIBLE);
    }


    @Override
    public int getItemCount() {
        if (null == mDatas) return 0;
        else return mDatas.size();
    }

    public class MyPostViewHolder extends RecyclerView.ViewHolder {

        ExpandableTextView mContentview;
        TextView expandable_text;
        LinearLayout ll_trade_image;
        LinearLayout ll_trade_image_for_only_one;
        LinearLayout ll_post;
        LinearLayout ll_comments;
        TextView tv_day;
        TextView tv_month;
        TextView tv_time;
        ImageView iv_triangle;
        TextView tv_sort_1;
        TextView tv_best;


        public MyPostViewHolder(View itemView) {
            super(itemView);
            mContentview = (ExpandableTextView) itemView.findViewById(R.id.tv_news_content);
            ll_trade_image = (LinearLayout) itemView.findViewById(R.id.ll_trade_image);
            ll_trade_image_for_only_one = (LinearLayout) itemView.findViewById(R.id.ll_trade_image_for_only_one);
            ll_post = (LinearLayout) itemView.findViewById(R.id.ll_post);
            ll_comments = (LinearLayout) itemView.findViewById(R.id.ll_comments);
            tv_day = (TextView) itemView.findViewById(R.id.tv_day);
            tv_month = (TextView) itemView.findViewById(R.id.tv_month);
            tv_time = (TextView) itemView.findViewById(R.id.tv_time);
            expandable_text = (TextView) itemView.findViewById(R.id.expandable_text);
            iv_triangle = (ImageView) itemView.findViewById(R.id.iv_triangle);
            tv_sort_1 = (TextView) itemView.findViewById(R.id.tv_sort_1);
            tv_best = (TextView) itemView.findViewById(R.id.tv_best);

            if (null != mContentview)
                mContentview.setExpandCollapseHintText(AppMain.getAppString(R.string.expandable_expand), AppMain.getAppString(R.string.expandable_collapse));
        }
    }

    private int computeImageLayoutMaxWidth() {
        // 获取屏幕宽度试试
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int screenDpW = px2dip(mContext, width);
        //计算图片区域允许的最大dp值
        int imageLayoutMaxDpW = screenDpW - 12 * 2 - 10 * 2 - 50 - 5 * 2;//这些都是扣除了margin，padding，以及其他组件的宽度. 这里，要参照list_item_post_2.xml
        return imageLayoutMaxDpW;
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}
